﻿package mvc_model
{
	import flash.events.EventDispatcher;
	import flash.events.Event;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.events.Event;
	
	// The super model class that every other model class extends.  It is designed to hold xml data
	// with iterating functionalit.
	public class Model extends EventDispatcher
	{
		private var _currentIndex:int;
		protected var totalItems:int;
		protected var loader:URLLoader;
		public static const MODEL_CHANGE:String = "MODEL_CHANGE";
		
		// can use any data type when you extend the model class
		public var data:*;
		
		public function Model()
		{
			_currentIndex = 0;
			
			loader = new URLLoader();
			loader.addEventListener(Event.COMPLETE, dataLoaded);
		}
		
		public function get currentIndex():int
		{
			return _currentIndex;
		}
		

		// request the data be loaded from the xml file
		public function load(request:URLRequest):void
		{
			loader.load(request);
		}
		
		// executes when the data has been succesfully loaded
		protected function dataLoaded(event:Event):void
		{
			data = loader.data;
			setCurrentIndex(_currentIndex);
		}
		
		// changing the currentIndex dispatches an update message to the view classes
		public function setCurrentIndex(index:int):void
		{
			_currentIndex = index;
			
			// control index flow for when data is being iterated over
			if (_currentIndex >= totalItems)
				_currentIndex = 0;
			else if (_currentIndex < 0)
				_currentIndex = totalItems - 1;
				
			updateData();
			dispatchEvent(new Event(Model.MODEL_CHANGE));
		}
		
		protected function updateData():void {}
	}
}